package org.redis.cluster.admin.server.controller;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.redis.cluster.admin.Constants;
import org.redis.cluster.admin.result.Result;
import org.redis.cluster.admin.result.ResultBuilder;
import org.redis.cluster.admin.server.service.ServerService;
import org.redis.cluster.config.ServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(Constants.API_ROOT+"/server")
public class ServerController {

	@Autowired
	private ServerService serverService;
	
	/**
	 * 返回服务
	 * @return
	 */
	@RequestMapping(value="",method=RequestMethod.GET)
	public Result getServers() {
		Collection<ServerConfig> servers=serverService.getServers();
		return ResultBuilder.success(servers);
	}
	
	/**
	 * info
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/{id}/info",method=RequestMethod.GET)
	public Result getInfo(@PathVariable String id) {
		String result=serverService.getInfo(id);
		if(result==null) {
			return ResultBuilder.failed("返回错误");
		}
		
		return ResultBuilder.success(result);
	}
	
	/**
	 * infos
	 * @return
	 */
	@RequestMapping(value="/infos",method=RequestMethod.GET)
	public Result getInfos() {
		Collection<ServerConfig> servers=serverService.getServers();
		if(CollectionUtils.isEmpty(servers)) {
			return ResultBuilder.failed("没有找到服务端");
		}
		
		Map<String,String> infos=new HashMap<String,String>(servers.size());
		for(ServerConfig server:servers) {
			infos.put(server.getId(), serverService.getInfo(server));
		}
		
		return ResultBuilder.success(infos);
	}
}